package com.itedge.solutionmanager.web.taskhandler.impl.solution;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;

import com.itedge.solutionmanager.domain.impl.Customer;
import com.itedge.solutionmanager.domain.impl.Solution;
import com.itedge.solutionmanager.enumeration.CustomerStatus;
import com.itedge.infrastructure.service.domain.IEnumeratedEntityService;
import com.itedge.infrastructure.service.process.IProcessService;
import com.itedge.infrastructure.service.task.ITaskService;
import com.itedge.infrastructure.service.taskdata.ITaskDataEntityService;
import com.itedge.infrastructure.stereotype.WebHandler;
import com.itedge.solutionmanager.taskdata.impl.solution.RegisterCustomerTaskData;
import com.itedge.solutionmanager.web.convert.ISOFormattingConversionServiceBean;
import com.itedge.infrastructure.web.taskhandler.TaskHandlerException;
import com.itedge.infrastructure.web.taskhandler.impl.AbstractTaskDataHandler;

@WebHandler
public class RegisterCustomerTaskDataHandler extends AbstractTaskDataHandler<RegisterCustomerTaskData, Solution> {

    private IEnumeratedEntityService<Customer> customerService;  
    
    @Autowired
    protected RegisterCustomerTaskDataHandler(ISOFormattingConversionServiceBean conversionService,
    		IProcessService<Solution> solutionProcessService,
    		ITaskDataEntityService<RegisterCustomerTaskData> registerCustomerTaskDataService,
    		ITaskService<RegisterCustomerTaskData, Solution> registerCustomerTaskService,
    		MessageSource messageSource, IEnumeratedEntityService<Customer> customerService) {
		super(conversionService, solutionProcessService, registerCustomerTaskDataService, 
				registerCustomerTaskService, messageSource);
		this.customerService = customerService;
	}
	
	@Override
	protected Class<RegisterCustomerTaskData> getTaskDataClass() {
		return RegisterCustomerTaskData.class;
	}
    
	@Override
	public Map<String,Object> loadTaskData(String taskId, Solution linkedSolution, Boolean forHistory) 
			throws TaskHandlerException {
		Map<String,Object> data = super.loadTaskData(taskId, linkedSolution, forHistory);
    	data.put("customers", Boolean.FALSE.equals(forHistory) ? 
    			customerService.findEntitiesByEnumeration(CustomerStatus.ACTIVE) : customerService.findAllEntities());
    	return data;
	}
	
	@Override
	public RegisterCustomerTaskData bindTaskData(HttpServletRequest request, Solution linkedSolution)
			throws TaskHandlerException {
		RegisterCustomerTaskData taskData = super.bindTaskData(request, linkedSolution);
		bindExistingCustomer(taskData, request);
		return taskData;
	}
	
	private void bindExistingCustomer(RegisterCustomerTaskData taskData, HttpServletRequest request) {
		if (!taskData.getIsExistingCust()) {
			taskData.setAssignedCustomer(null);
		}
	}
	
}
